package com.yogee.topseller.activity;

import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import com.yogee.core.base.HttpActivity;
import com.yogee.core.http.listener.HttpOnNextListener;
import com.yogee.core.http.subscribers.BaseSubscriber;
import com.yogee.core.utils.ToastUtils;
import com.yogee.topseller.R;
import com.yogee.topseller.activity.subscription.AppointProductActivity;
import com.yogee.topseller.activity.subscription.SubscriptionProductActivity;
import com.yogee.topseller.adapter.ProductInterestedRvAdapter;
import com.yogee.topseller.bean.CollectBean;
import com.yogee.topseller.bean.PKBean;
import com.yogee.topseller.bean.ProductInfoBean;
import com.yogee.topseller.bean.ResultBean;
import com.yogee.topseller.bean.ShareProductBean;
import com.yogee.topseller.http.HttpManager;
import com.yogee.topseller.layout.GoodBadDialogFragment;
import com.yogee.topseller.layout.ProductDetailsMenuLayout;
import com.yogee.topseller.utils.AppUtil;
import com.yogee.topseller.utils.GlideUtils;
import com.yogee.topseller.view.FlowLayout;
import com.yogee.topseller.view.HoveringScrollview;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 产品详情 activity
 *
 * @auathor ${XiaoJianghong}
 * @date 2017/6/28.
 */

public class ProductDetailsActivity_old extends HttpActivity implements HoveringScrollview.OnScrollListener {

    @BindView(R.id.product_laiyuan_tv)
    TextView productLaiyuanTv;
    @BindView(R.id.product_cuoshi_tv)
    TextView productCuoshiTv;
    private ProgressDialog mProgressDialog;
    private PopupWindow popupWindow;
    private boolean isExpend = false;

    // 下载失败
    public static final int DOWNLOAD_ERROR = 2;
    // 下载成功
    public static final int DOWNLOAD_SUCCESS = 1;
    private File file1;

    @BindView(R.id.details_interested_rv)
    RecyclerView interestedRv;
    @BindView(R.id.details_scrollview)
    HoveringScrollview detailsScrollview;
    @BindView(R.id.details_high_ll)
    LinearLayout detailsHighLl;
    @BindView(R.id.details_account_ll)
    LinearLayout detailsAccountLl;
    @BindView(R.id.details_more_ll)
    LinearLayout detailsMoreLl;
    @BindView(R.id.details_lable_flowlayout)
    FlowLayout lableFlowlayout;
    @BindView(R.id.product_basic_name_tv)
    TextView productBasicNameTv;
    @BindView(R.id.product_basic_rating_tv)
    TextView productBasicRatingTv;
    @BindView(R.id.product_basic_explain_tv)
    TextView productBasicExplainTv;
    @BindView(R.id.product_basic_status_tv)
    TextView productBasicStatusTv;
    @BindView(R.id.product_basic_sizeratio_tv)
    TextView productBasicSizeratioTv;
    @BindView(R.id.product_basic_type_tv)
    TextView productBasicTypeTv;
    @BindView(R.id.product_basic_organization_tv)
    TextView productBasicOrganizationTv;
    @BindView(R.id.product_basic_method_tv)
    TextView productBasicMethodTv;
    @BindView(R.id.product_basic_field_tv)
    TextView productBasicFieldTv;
    @BindView(R.id.product_basic_deadline_tv)
    TextView productBasicDeadlineTv;
    @BindView(R.id.product_basic_purchasestart_tv)
    TextView productBasicPurchasestartTv;
    @BindView(R.id.product_basic_scalestart_tv)
    TextView productBasicScalestartTv;
    @BindView(R.id.product_basic_mortgage_tv)
    TextView productBasicMortgageTv;
    @BindView(R.id.product_basic_structured_tv)
    TextView productBasicStructuredTv;
    @BindView(R.id.product_subject_tv)
    TextView productSubjectTv;
    @BindView(R.id.details_account_name_tv)
    TextView productAccountRemarkTv;
    @BindView(R.id.product_highlights_light_tv)
    TextView productLightTv;
    @BindView(R.id.details_lable_more_iv)
    ImageView detailsLableMoreIv;
    @BindView(R.id.details_title_tv)
    TextView detailsTitleTv;
    @BindView(R.id.details_img_iv)
    ImageView detailsImgIv;
    @BindView(R.id.details_message_tv)
    TextView detailsMessageTv;
    @BindView(R.id.details_cutoff_date_ll)
    LinearLayout cutoffDateLl;
    @BindView(R.id.details_star_money_ll)
    LinearLayout starMoneyLl;
    @BindView(R.id.details_lost_date_tv)
    TextView detailsLostDateTv;
    @BindView(R.id.details_star_money_tv)
    TextView detailsStarMoneyTv;
    @BindView(R.id.details_rate_money1_tv)
    TextView money1Tv;
    @BindView(R.id.details_rate_profit1_tv)
    TextView profit1Tv;
    @BindView(R.id.details_rate_rebate1_tv)
    TextView rebate1Tv;
    @BindView(R.id.details_rate_money2_tv)
    TextView money2Tv;
    @BindView(R.id.details_rate_profit2_tv)
    TextView profit2Tv;
    @BindView(R.id.details_rate_rebate2_tv)
    TextView rebate2Tv;
    @BindView(R.id.details_rate_money3_tv)
    TextView money3Tv;
    @BindView(R.id.details_rate_profit3_tv)
    TextView profit3Tv;
    @BindView(R.id.details_rate_rebate3_tv)
    TextView rebate3Tv;
    @BindView(R.id.details_state_type_tv)
    TextView stateTypeTv;
    @BindView(R.id.details_pro_tv)
    TextView proTv;
    @BindView(R.id.pk)
    RelativeLayout pk;
    @BindView(R.id.details_state_pb)
    ProgressBar pb;
    @BindView(R.id.details_state_pro_tv)
    TextView pbTv;
    @BindView(R.id.details_collection_tv)
    TextView collectionTv;
    @BindView(R.id.details_lable_tv)
    TextView lableTv;
    @BindView(R.id.details_compare_num_tv)
    TextView numTv;
    @BindView(R.id.button_ll)
    LinearLayout buttonLl;
    @BindView(R.id.product_details_menu_layout)
    ProductDetailsMenuLayout menuLayout;
    @BindView(R.id.details_base_ll)
    LinearLayout baseLl;
    @BindView(R.id.details_material_ll)
    LinearLayout materialLl;
    @BindView(R.id.details_rate_ll)
    LinearLayout rateLl;
    @BindView(R.id.details_rate_1_ll)
    LinearLayout rateLl1;
    @BindView(R.id.details_rate_2_ll)
    LinearLayout rateLl2;
    @BindView(R.id.details_rate_3_ll)
    LinearLayout rateLl3;

    private PKBean pkBean;

    private ProductInfoBean bean;

    private ProductInterestedRvAdapter interestedRvAdapter;

    private int high_top, account_top, more_top, base_top, buttonLlTop;
    private String id, userId;
    private String name;
    private String recruitmentStatus;
    private String phone;
    private String isFast = "0";
    private GoodBadDialogFragment dialogFragment;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_product_details_copy;
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        high_top = detailsHighLl.getTop();
        account_top = detailsAccountLl.getTop();
        more_top = detailsMoreLl.getTop();
        buttonLlTop = buttonLl.getTop();
        base_top = baseLl.getTop();
        menuLayout.setViewScrollY(detailsScrollview, base_top, high_top, account_top, more_top);
    }

    @Override
    protected void initView() {
        if (getIntent() != null) {
            id = getIntent().getStringExtra("id");
            isFast = getIntent().getStringExtra("isFast");
        }
        userId = AppUtil.getUserId(this);
        interestedRv.setLayoutManager(new LinearLayoutManager(this));
        interestedRvAdapter = new ProductInterestedRvAdapter(this);
        interestedRv.setAdapter(interestedRvAdapter);

        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        mProgressDialog.setCancelable(false);

        detailsScrollview.setOnScrollListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        productInfo(id, isFast);
    }

    @OnClick({R.id.details_lable_more_ll, R.id.details_title_back_rl, R.id.details_base_rl, R.id.details_duibi_tv, R.id.pk, R.id.details_high_tv, R.id.etails_plus_rl, R.id.details_phone_rl, R.id.details_account_tv, R.id.details_more_t, R.id.product_basic_copy_tv, R.id.product_highlights_copy_tv, R.id.product_account_copy_tv, R.id.details_collection_rl, R.id.details_pro_tv, R.id.details_share_rl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.details_title_back_rl:
                finish();
                break;
            case R.id.pk://一秒看优劣
                if (AppUtil.isExamine(this)) {
                    pkInfo(AppUtil.getUserId(this), id);
                } else {
                    pkInfo("", id);
                }
                break;
            case R.id.details_duibi_tv://对比
                if (AppUtil.isExamined(this)) {
                    startActivity(new Intent(this, ProductCompareActivity.class));
                }
                break;
            case R.id.details_base_rl:
                detailsScrollview.smoothScrollTo(0, base_top - 80);
                menuLayout.setPosition(0);
                break;
            case R.id.details_high_tv:
                detailsScrollview.smoothScrollTo(0, high_top - 80);
                menuLayout.setPosition(1);
                break;
            case R.id.details_account_tv:
                detailsScrollview.smoothScrollTo(0, account_top - 80);
                menuLayout.setPosition(2);
                break;
            case R.id.details_more_t:
                detailsScrollview.smoothScrollTo(0, more_top - 80);
                menuLayout.setPosition(3);
                break;
            case R.id.details_phone_rl://咨询
                if (!phone.equals("")) {
                    Intent intent = new Intent(Intent.ACTION_DIAL);
                    Uri data = Uri.parse("tel:" + phone);
                    intent.setData(data);
                    startActivity(intent);
                }
                break;
            case R.id.details_share_rl://分享
                if (AppUtil.isExamined(this))
                    showBottomPopuWindow();
                break;
            case R.id.product_basic_copy_tv://基本资料复制
                String rzje = money1Tv.getText().toString(),jzsy=profit1Tv.getText().toString();
                if (money2Tv.getText().toString().length() != 0){
                    rzje += " "+money2Tv.getText().toString();
                }
                if (money3Tv.getText().toString().length() != 0){
                    rzje += " "+money3Tv.getText().toString();
                }
                if (profit2Tv.getText().toString().length() != 0){
                    jzsy += " "+profit2Tv.getText().toString();
                }
                if (profit3Tv.getText().toString().length() != 0){
                    jzsy += " "+profit3Tv.getText().toString();
                }
                ProductInfoBean.BasicBean basicBean = bean.getBasic().get(0);
                String basic = "【产品名称】:" + "\t" + basicBean.getName() + "\n" +
                        "【评级等级】:" + "\t" + basicBean.getRating() + "\n" +
                        "【说明】:" + "\t" + basicBean.getExplain() + "\n" +
                        "【基金状态】:" + "\t" + basicBean.getStatus() + "\n" +
                        "【大小配比】:" + "\t" + basicBean.getSizeRatio() + "\n" +
                        "【收益类型】:" + "\t" + basicBean.getType() + "\n" +
                        "【发型机构】:" + "\t" + basicBean.getOrganization() + "\n" +
                        "【付息方式】:" + "\t" + basicBean.getMethod() + "\n" +
                        "【投资领域】:" + "\t" + basicBean.getField() + "\n" +
                        "【产品期限】:" + "\t" + basicBean.getDeadline() + "\n" +
                        "【认购起点】:" + "\t" + basicBean.getPurchaseStart() + "\n" +
                        "【起售日】:" + "\t" + basicBean.getScaleStart() + "\n" +
                        "【抵/质押率】:" + "\t" + basicBean.getMortgage() + "\n" +
                        "【是否机构化】:" + "\t" + basicBean.getStructured()+ "\n" +
                        "【认证金额】:" + "\t" + rzje+ "\n" +
                        "【基准收益】:" + "\t" + jzsy;

                ClipboardManager basicCopy = (ClipboardManager) this
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                basicCopy.setText(basic);
                ToastUtils.showToast(this, "复制成功");
                break;
            case R.id.product_highlights_copy_tv://亮点复制
                ProductInfoBean.HighlightsBean highlightsBean = bean.getHighlights().get(0);
                String highlights = "【产品亮点】:" + "\t" + highlightsBean.getLight();

                ClipboardManager highlightsCopy = (ClipboardManager) this
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                highlightsCopy.setText(highlights);
                ToastUtils.showToast(this, "复制成功");
                break;
            case R.id.product_account_copy_tv://募集账户复制
                ProductInfoBean.AccountBean accountBean = bean.getAccount().get(0);
                String account = accountBean.getRemark();
                ClipboardManager accountCopy = (ClipboardManager) this
                        .getSystemService(Context.CLIPBOARD_SERVICE);
                accountCopy.setText(account);
                ToastUtils.showToast(this, "复制成功");
                break;
            case R.id.details_collection_rl://收藏
                if (AppUtil.isExamined(this)) {
                    String userid = AppUtil.getUserId(this);
                    collect(userid, id);
                }
                break;
            case R.id.details_pro_tv://预约
                if (AppUtil.isExamined(this)) {
                    if (recruitmentStatus.equals("募集中")) {//预约
                        startActivity(new Intent(this, AppointProductActivity.class).putExtra("id", id).putExtra("name", name).putExtra("startAmount", bean.getStartAmount()).putExtra("isFast", isFast));
                    } else if (recruitmentStatus.equals("预热中")) {//认购
                        startActivity(new Intent(this, SubscriptionProductActivity.class).putExtra("id", id).putExtra("name", name).putExtra("startAmount", bean.getStartAmount()).putExtra("isFast", isFast));
                    }
                }
                break;
            case R.id.etails_plus_rl://添加对比
                addCompare(id, userId);
                break;
            case R.id.details_lable_more_ll://展开全部标签
                /*ProductInfoBean.InfoBean infoBean = bean.getInfo().get(0);
                List<String> list = Arrays.asList(infoBean.getLabels().split(","));

                lableFlowlayout.cleanTag();
                lableFlowlayout.setDatas(list);
                detailsLableMoreIv.setVisibility(View.GONE);*/
                setHight(lableFlowlayout);
                break;
        }
    }

    /**
     * 设置“标签”展开与否
     *
     * @param lableFlowlayout
     */
    public void setHight(FlowLayout lableFlowlayout) {
        LinearLayout.LayoutParams params = null;
        if (isExpend) {
            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            detailsLableMoreIv.setImageResource(R.mipmap.product_packup_black);
        } else {
            params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, AppUtil.dip2px(this, 40));
            detailsLableMoreIv.setImageResource(R.mipmap.product_pulldown_red);
        }
        detailsLableMoreIv.setVisibility(View.VISIBLE);
        lableFlowlayout.setLayoutParams(params);
        isExpend = !isExpend;
    }

    /**
     * 产品详情
     *
     * @param id
     */
    private void productInfo(String id, String isFast) {
        HttpManager.getInstance().productInfo(AppUtil.getUserId(this), id, "0", "10", isFast).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ProductInfoBean>() {
            @Override
            public void onNext(ProductInfoBean o) {
                bean = o;
                setViewData(o);
            }
        }, this));
    }

    private void setViewData(ProductInfoBean bean) {
        //pk
        pkBean = new PKBean(bean.getIsCollateralize(), bean.getBasic().get(0).getName(), bean.getInvestmentTerm(), bean.getExpectReturn(), bean.getCommission());
        //对比
        if (bean.getNum().equals("0")) {
            numTv.setVisibility(View.GONE);
        } else {
            numTv.setText(bean.getNum());
        }
        //基本资料
        ProductInfoBean.BasicBean basicBean = bean.getBasic().get(0);
        name = basicBean.getName();
        phone = bean.getPhone();
        productBasicNameTv.setText(basicBean.getName());
        productBasicRatingTv.setText(basicBean.getRating());
        productBasicExplainTv.setText(basicBean.getExplain());
        productBasicStatusTv.setText(basicBean.getStatus());
        productBasicSizeratioTv.setText(basicBean.getSizeRatio());
        productBasicTypeTv.setText(basicBean.getType());
        productBasicOrganizationTv.setText(basicBean.getOrganization());
        productBasicMethodTv.setText(basicBean.getMethod());
        productBasicFieldTv.setText(basicBean.getField());
        productBasicDeadlineTv.setText(basicBean.getDeadline());
        productBasicPurchasestartTv.setText(basicBean.getPurchaseStart());
        productBasicScalestartTv.setText(basicBean.getScaleStart());
        productBasicMortgageTv.setText(basicBean.getMortgage());
        productBasicStructuredTv.setText(basicBean.getStructured());
        if (bean.getIsCollect().equals("1")) {
            collectionTv.setText("已收藏");
        } else {
            collectionTv.setText("收藏");
        }

        //感兴趣产品
        interestedRvAdapter.addData(bean.getInterest());
        //融资主体
        productSubjectTv.setText(bean.getSubject());
        //--h
        //还款来源
        if ("".equals(bean.getLaiyuan())) {
            productLaiyuanTv.setText("暂无数据");
        } else {
            productLaiyuanTv.setText(bean.getLaiyuan());
        }
        //风控措施
        if ("".equals(bean.getCuoshi())) {
            productCuoshiTv.setText("暂无数据");
        } else {
            productCuoshiTv.setText(bean.getCuoshi());
        }
        //--h
        //募集账户
        ProductInfoBean.AccountBean accountBean = bean.getAccount().get(0);
        productAccountRemarkTv.setText(accountBean.getRemark());
        //产品亮点
        productLightTv.setText(bean.getHighlights().get(0).getLight());
        //产品信息
        ProductInfoBean.InfoBean infoBean = bean.getInfo().get(0);
        List<String> list = Arrays.asList(infoBean.getLabels().split(","));
       /* if (list.size() > 4) {
            List<String> labels = list.subList(0, 4);
            lableFlowlayout.cleanTag();
            lableFlowlayout.setDatas(labels);
            detailsLableMoreIv.setVisibility(View.VISIBLE);
        } else {
            lableFlowlayout.cleanTag();
            lableFlowlayout.setDatas(list);
            detailsLableMoreIv.setVisibility(View.GO NE);
        }*/
        lableFlowlayout.cleanTag();
        lableFlowlayout.setDatas(list);
        setHight(lableFlowlayout);

        detailsTitleTv.setText(infoBean.getName());
        GlideUtils.defultImage(this, infoBean.getImg(), detailsImgIv);
        detailsMessageTv.setText(infoBean.getCurrentInfo());
        if (infoBean.getCutoffDate().equals("")) {
            detailsLostDateTv.setText("");
        } else {
            detailsLostDateTv.setText(infoBean.getCutoffDate());
        }
        if (infoBean.getDepositDate().equals("")) {
            detailsStarMoneyTv.setText("");
        } else {
            detailsStarMoneyTv.setText(infoBean.getDepositDate());
        }
        stateTypeTv.setText(infoBean.getRecruitmentStatus());
        recruitmentStatus = infoBean.getRecruitmentStatus();
        pbTv.setText(infoBean.getShelfState() + "%");
        if (!infoBean.getShelfState().equals("")) {
            String[] splitPres = new String[2];
            splitPres = infoBean.getShelfState().split("\\.");
            if (splitPres.length > 1) {
                pb.setProgress(Integer.parseInt(splitPres[0]));
            } else {
                pb.setProgress(Integer.parseInt(infoBean.getShelfState()));
            }
        }
        lableTv.setText(infoBean.getFundUse());
        if (infoBean.getRecruitmentStatus().equals("预热中")) {
            proTv.setText("认购");
        } else if (infoBean.getRecruitmentStatus().equals("募集中")) {
            proTv.setText("预约");
        } else {
            proTv.setText("售罄");
            proTv.setClickable(false);
            proTv.setTextColor(Color.parseColor("#ffffff"));
            proTv.setBackgroundColor(getResources().getColor(R.color.gray));
        }
        //收益率
        List<ProductInfoBean.RateBean> rateBeen = bean.getRate();
        if (rateBeen != null && rateBeen.size() > 0) {//如果收益率为空
            switch (rateBeen.size()) {
                case 1:
                    money1Tv.setText(rateBeen.get(0).getMoney());
                    profit1Tv.setText(rateBeen.get(0).getProfit());
                    rebate1Tv.setText(rateBeen.get(0).getRebate());

                    rateLl3.setVisibility(View.GONE);
                    rateLl2.setVisibility(View.GONE);
                    break;
                case 2:
                    money1Tv.setText(rateBeen.get(0).getMoney());
                    profit1Tv.setText(rateBeen.get(0).getProfit());
                    rebate1Tv.setText(rateBeen.get(0).getRebate());

                    money2Tv.setText(rateBeen.get(1).getMoney());
                    profit2Tv.setText(rateBeen.get(1).getProfit());
                    rebate2Tv.setText(rateBeen.get(1).getRebate());

                    rateLl3.setVisibility(View.GONE);
                    break;
                case 3:
                    money1Tv.setText(rateBeen.get(0).getMoney());
                    profit1Tv.setText(rateBeen.get(0).getProfit());
                    rebate1Tv.setText(rateBeen.get(0).getRebate());

                    money2Tv.setText(rateBeen.get(1).getMoney());
                    profit2Tv.setText(rateBeen.get(1).getProfit());
                    rebate2Tv.setText(rateBeen.get(1).getRebate());

                    money3Tv.setText(rateBeen.get(2).getMoney());
                    profit3Tv.setText(rateBeen.get(2).getProfit());
                    rebate3Tv.setText(rateBeen.get(2).getRebate());
                    break;
            }
        } else {
            rateLl.setVisibility(View.GONE);
        }

        //材料
        final List<ProductInfoBean.MaterialBean> materialBeen = bean.getMaterial();
        materialLl.removeAllViews();
        if (materialBeen.size() > 0 && materialBeen != null) {
            for (int i = 0; i < materialBeen.size(); i++) {
                View v = LayoutInflater.from(this).inflate(R.layout.product_details_material_layout, null);
                ImageView iv = (ImageView) v.findViewById(R.id.material_iv);
                TextView tv = (TextView) v.findViewById(R.id.material_tv);
                if (materialBeen.get(i).getType().equals("doc")) {
                    iv.setImageResource(R.mipmap.product_w_blue);
                } else if (materialBeen.get(i).getType().equals("pdf")) {
                    iv.setImageResource(R.mipmap.product_p_red);
                } else {
                    iv.setImageResource(R.mipmap.product_e_green);
                }
                tv.setText(materialBeen.get(i).getName());
                RelativeLayout rl = (RelativeLayout) v.findViewById(R.id.material_rl);
                final int finalI = i;

                rl.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        download(materialBeen.get(finalI).getUrl(), materialBeen.get(finalI).getName());
                    }
                });
                materialLl.addView(v);
            }
        }
    }

    private void collect(String userid, String id) {
        HttpManager.getInstance().collect(userid, id).compose(bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<CollectBean>() {
            @Override
            public void onNext(CollectBean o) {
                if (o.getState().equals("0")) {
                    collectionTv.setText("已收藏");
                    ToastUtils.showToast(ProductDetailsActivity_old.this, "收藏成功");
                } else {
                    collectionTv.setText("收藏");
                    ToastUtils.showToast(ProductDetailsActivity_old.this, "已取消收藏");
                }
            }
        }, this));
    }

    private void download(final String url, String name) {
        mProgressDialog.show();
        //截取最后3位 作为文件名
        String s = name;
        Log.d("asbdasd", s);
        //文件存储
        file1 = new File(Environment.getExternalStorageDirectory(), getFileName(s));
        new Thread() {
            public void run() {

                File haha = new File(file1.getAbsolutePath());
                //判断是否有此文件
                if (haha.exists()) {
                    //有缓存文件,拿到路径 直接打开
                    Message msg = Message.obtain();
                    msg.obj = haha;
                    msg.what = DOWNLOAD_SUCCESS;
                    handler.sendMessage(msg);
                    mProgressDialog.dismiss();
                    return;
                }
                //本地没有此文件 则从网上下载打开
                File downloadfile = downLoad(url, file1.getAbsolutePath(), mProgressDialog);
                Message msg = Message.obtain();
                if (downloadfile != null) {
                    // 下载成功,安装....
                    msg.obj = downloadfile;
                    msg.what = DOWNLOAD_SUCCESS;
                } else {
                    // 提示用户下载失败.
                    msg.what = DOWNLOAD_ERROR;
                }
                handler.sendMessage(msg);
                mProgressDialog.dismiss();
            }
        }.start();
    }

    /**
     * 下载完成后  直接打开文件
     */
    Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DOWNLOAD_SUCCESS:
                    File file = (File) msg.obj;
                    Intent intent = new Intent("android.intent.action.VIEW");
                    intent.addCategory("android.intent.category.DEFAULT");
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setDataAndType(Uri.fromFile(file), "application/pdf");
                    startActivity(Intent.createChooser(intent, "请选择要打开的工具"));
                    break;
                case DOWNLOAD_ERROR:
                    ToastUtils.showToast(ProductDetailsActivity_old.this, "文件加载失败");
                    break;
            }
        }
    };

    /**
     * 传入文件 url  文件路径  和 弹出的dialog  进行 下载文档
     */
    public static File downLoad(String serverpath, String savedfilepath, ProgressDialog pd) {
        try {
            URL url = new URL(serverpath);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            if (conn.getResponseCode() == 200) {
                int max = conn.getContentLength();
                pd.setMax(max);
                InputStream is = conn.getInputStream();
                File file = new File(savedfilepath);
                FileOutputStream fos = new FileOutputStream(file);
                int len = 0;
                byte[] buffer = new byte[1024];
                int total = 0;
                while ((len = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len);
                    total += len;
                    pd.setProgress(total);
                }
                fos.flush();
                fos.close();
                is.close();
                return file;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getFileName(String serverurl) {
        return serverurl.substring(serverurl.lastIndexOf("/") + 1);
    }

    private void addCompare(final String proId, String userId) {
        HttpManager.getInstance().addCompare(proId, userId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ResultBean>() {
            @Override
            public void onNext(ResultBean o) {
                if (o.getResult().equals("1")) {
                    ToastUtils.showToast(ProductDetailsActivity_old.this, "添加成功");
                    productInfo(proId, isFast);
                }
            }
        }, this));
    }

    private void pkInfo(String userId, String proId) {
        HttpManager.getInstance().pkInfo(userId, proId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<PKBean>() {
            @Override
            public void onNext(PKBean o) {
                dialogFragment = new GoodBadDialogFragment();
                Bundle bundle = new Bundle();
                bundle.putSerializable("pk1", pkBean);
                bundle.putSerializable("pk2", o);
                bundle.putString("nowId", id);
                dialogFragment.setArguments(bundle);
                dialogFragment.show(getFragmentManager(), "");
            }
        }, this));
    }

    /**
     * 底部弹出层
     */
    private void showBottomPopuWindow() {
        LinearLayout rootView = (LinearLayout) LayoutInflater.from(this).inflate(
                R.layout.dialog_share_board, null);

        popupWindow = new PopupWindow(rootView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        TextView cancelT = (TextView) rootView.findViewById(R.id.btn_cancel);
        cancelT.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        LinearLayout wechatL = (LinearLayout) rootView.findViewById(R.id.share_wechat);
        wechatL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                shareProduct(AppUtil.getUserId(ProductDetailsActivity_old.this), id, SHARE_MEDIA.WEIXIN);
                popupWindow.dismiss();
            }
        });
        LinearLayout wxCircleL = (LinearLayout) rootView.findViewById(R.id.share_wxcircle);
        wxCircleL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                shareProduct(AppUtil.getUserId(ProductDetailsActivity_old.this), id, SHARE_MEDIA.WEIXIN_CIRCLE);
                popupWindow.dismiss();
            }
        });
        LinearLayout sinaL = (LinearLayout) rootView.findViewById(R.id.share_sina);
        sinaL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                shareProduct(AppUtil.getUserId(ProductDetailsActivity_old.this), id, SHARE_MEDIA.QQ);
                popupWindow.dismiss();
            }
        });
        LinearLayout emailL = (LinearLayout) rootView.findViewById(R.id.share_email);
        emailL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AppUtil.isFastDoubleClick(1000)) {
                    return;
                }
                shareProduct(AppUtil.getUserId(ProductDetailsActivity_old.this), id, SHARE_MEDIA.QZONE);
                popupWindow.dismiss();
            }
        });
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        popupWindow.showAtLocation(rootView, Gravity.BOTTOM, 0, 0);
    }

    private void shareProduct(String userId, String proId, final SHARE_MEDIA type) {
        HttpManager.getInstance().shareProduct(userId, proId).compose(this.bindRecycler()).subscribe(new BaseSubscriber(new HttpOnNextListener<ShareProductBean>() {
            @Override
            public void onNext(ShareProductBean o) {

                share(o.getName(), o.getContent(), o.getUrl(), o.getImg(), type);
            }
        }, this));
    }

    /**
     * 分享到平台
     *
     * @param plarform
     */
    private void share(String title, String content, String url, String img, SHARE_MEDIA plarform) {
        UMImage thumb = new UMImage(ProductDetailsActivity_old.this, img);
        UMWeb web = new UMWeb(url);
        web.setThumb(thumb);
        web.setDescription(content);
        web.setTitle(title);
        new ShareAction(ProductDetailsActivity_old.this)
                .withMedia(web)
                .setPlatform(plarform)
                .setCallback(umShareListener)
                .share();
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onStart(SHARE_MEDIA platform) {
            //分享开始的回调
        }

        @Override
        public void onResult(SHARE_MEDIA platform) {
            Log.d("plat", "platform" + platform);
            ToastUtils.showToast(ProductDetailsActivity_old.this, " 分享成功啦");
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtils.showToast(ProductDetailsActivity_old.this, " 分享失败啦");
            if (t != null) {
                Log.d("throw", "throw:" + t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtils.showToast(ProductDetailsActivity_old.this, " 分享取消了");
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onScroll(int scrollY) {
        if (scrollY >= buttonLlTop) {
            menuLayout.setVisibility(View.VISIBLE);
        } else {
            menuLayout.setVisibility(View.GONE);
            menuLayout.setPosition(0);
        }

    }

}